<template>
  <div class="home">
    <div class="detail_box">
      <!-- 操作 -->
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item">
            <label>关键词：</label>
            <el-input type="text" clearable placeholder="请输入关键词" v-model="keyword"></el-input>
          </div>

          <div class="operate_item">
            <label>用户ID：</label>
            <el-input type="text" clearable placeholder="请输入用户ID" v-model="id"></el-input>
          </div>

          <div class="operate_item" v-if="userType ==0 || userType ==1 ||userType ==4 ">
            <label>销售：</label>
            <el-select
              filterable
              clearable
              v-model="refereeIds"
              placeholder="请选择销售">
              <el-option
                v-for="(item,index) in refereeOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>

          <div class="operate_item">
            <label>状态：</label>
            <el-select
              filterable
              clearable
              v-model="status"
              placeholder="请选择状态">
              <el-option
                v-for="(item,index) in statusOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo(1)">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
        <div class="btn_box" >
          <div v-if="btn.import">
            <el-upload ref="upload"
                       class="avatar-uploader"
                       :action="uploadUrl"
                       :headers="{token:token}"
                       :data="param"
                       accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                       :show-file-list="false"
                       :on-success="importSuccess">
              <el-button type="success" class="operate_btn import_btn">导入</el-button>
            </el-upload>
          </div>
          <span class="operate_btn search_btn" v-if="btn&&btn.merge" :type="opType" @click="openMerge(1,1)" >合并用户</span>
          <span class="operate_btn search_btn" v-if="btn&&btn.transfer" :type="opType" @click="openMerge(1,2)" >转移用户</span>
          <span class="operate_btn export_btn" v-if="btn && btn.phoneUser" @click="openMerge(2)">新增电话用户</span>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table_box">
        <el-table
          border
          v-loading="loading"
          :header-cell-style="tableHeader"
          ref="multipleTable"
          :data="tableInfo"
          tooltip-effect="dark"
          @sort-change="getChange"
          style="width: 100%;">
          <el-table-column
            width="80"
            prop="id"
            label="ID">
          </el-table-column>

          <el-table-column
            label="微信名称" >
            <template slot-scope="scope">
              <p @click="openPopup(scope.row.id)">{{scope.row.wxName? scope.row.wxName : '——'}}</p>
            </template>
          </el-table-column>
          <el-table-column
            label="备注" >
            <template slot-scope="scope">
              <p @click="openPopup(scope.row.id)">{{scope.row.remark ? scope.row.remark : '——'}}</p>
            </template>
          </el-table-column>
          <el-table-column
            width="80"
            label="微信头像">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.wxPhoto" class="icon" v-if="scope.row.wxPhoto">
                <p v-else>——</p>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="numbers"
            label="剩余水票" width="100">
            <template slot-scope="scope">{{scope.row.numbers?scope.row.numbers:0}}</template>
          </el-table-column>

          <el-table-column
            width="170"
            label="额度(可/已使用额度)">
            <template slot-scope="scope">
              <p>
                <i class="rate">{{scope.row.authRatio ? finalNum(scope.row.authRatio) : 0}}%</i>
                (<span title="可使用额度" class="check_btn">{{scope.row.userAuth?scope.row.userAuth:0}}</span>/<span title="已使用额度" class="used">{{scope.row.userAuthUsed?scope.row.userAuthUsed:0}}</span>)
              </p>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="money"
            label="历史充值(元)" width="140">
            <template slot-scope="scope">{{scope.row.money?scope.row.money:0}}</template>
          </el-table-column>
          <el-table-column
            prop="userAuth"
            label="已付押金/手上桶数" width="150">
            <template slot-scope="scope">{{scope.row.pledge?scope.row.pledge:0}}/{{scope.row.productNum?scope.row.productNum:0}}</template>
          </el-table-column>
          <el-table-column
            prop="2"
            sortable="custom"
            label="已/未付押金桶" width="140">
            <template slot-scope="scope"><span :class="parseFloat(scope.row.pledgeRatio)>3 ? 'color':''">{{scope.row.pledgeRatio ? finalNum(scope.row.pledgeRatio):0}}%</span></template>
          </el-table-column>
          <el-table-column
            width="120"
            label="所属销售">
            <template slot-scope="scope">{{scope.row.refereeName ? scope.row.refereeName : '——'}}</template>
          </el-table-column>
          <el-table-column
            width="100"
            label="状态" v-if="!(btn.freeze||btn.unfreeze)">
            <template slot-scope="scope">
              <div :style="'color:'+(scope.row.enable===1?'#67c430':'#e60000')">
                {{scope.row.enable===1?'可用':'冻结'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            prop="2"
            width="100" v-if="btn.freeze||btn.unfreeze">
            <template slot-scope="scope">
              <div>
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="deleteItem(scope.row,scope.$index)"
                  v-model="scope.row.enable">
                </el-switch>
                <span class="normal" v-if="scope.row.enable===1">可用</span>
                <span class="unusual" v-else>冻结</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            width="160"
            sortable
            prop="modifyTime"
            label="修改时间">
            <template slot-scope="scope">
              <p style="text-align: left">{{formatTime(scope.row.modifyTime)}}</p>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            v-if="btn&&(btn.detail || btn.change || btn.remark || btn.product || btn.order || btn.userBind || btn.unbind || btn.address||btn.reserve||btn.refund||btn.log)"
            width="240">
            <template slot-scope="scope">
              <div class="table_btn">
                <span class="change_info" @click="changeSales(scope.row,1)" v-if="btn.remark">备注</span>
                <span class="change_info" @click="openPopup(scope.row.id)" v-if="btn.detail">详情</span>
                <span class="change_info" @click="bindUserChild(scope.row,1)" v-if="scope.row.parentId===0 && btn.userBind">绑定下级</span>
                <span class="change_info"  @click="bindUserChild(scope.row,2)" v-if="scope.row.parentId===0 && btn.removeBind">解绑下级</span>
                <span class="change_info delete_btn"  @click="changeSales(scope.row,2)" v-if="btn.change">替换销售</span>
                <span class="change_info"  @click="gotoDetail(scope.row,1)" v-if="btn.product">用户商品</span>
                <span class="change_info"  @click="gotoDetail(scope.row,2)" v-if="btn.address">收货地址</span>
                <span class="change_info"  @click="gotoDetail(scope.row,3)" v-if="btn.log">商品日志</span>
                <span class="change_info"  @click="gotoDetail(scope.row,4)" v-if="btn.order">用户订单</span>
                <span class="change_info"  @click="gotoDetail(scope.row,5)" v-if="btn.reserve">预约单</span>
                <span class="change_info"  @click="gotoDetail(scope.row,6)" v-if="btn.refund">退货单</span>
                <span class="change_info"  @click="gotoDetail(scope.row,7)" v-if="btn.change">变更单</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="record_page">
        <span class="page_count">共<i>{{totals}}</i>条</span>
        <el-pagination
          @size-change="sizeChange"
          @current-change="getTableInfo"
          background
          :current-page="currentPage"
          :page-sizes="[15, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes,jumper"
          :total="totals">
        </el-pagination>
      </div>
    </div>
    <edit v-if="isPop" :userId="userId" @listenToChild="listenToEdit"></edit>
    <changeSale v-if="isChangeSale" :userId="userId" :type="type"  @listenToChild="listenToEdit"></changeSale>
    <importData v-if="isImport" :data="importData" @listenToChild="isImport=false"></importData>
    <mergeUser v-if="isMerge" :type="opType" @listenToChild="listenToEdit"></mergeUser>
    <addPhoneUser v-if="isAddPhoneUser" @listenToChild="listenToEdit"></addPhoneUser>
    <el-dialog :title="(userName+(bindType===1?'绑定':'解绑')+'下级')" :visible.sync="isBind" width="80%" @close="closeBind" :append-to-body="true" v-dialogDrag>
      <bindChild :userId="userId"  v-if="isBind&&bindType===1" @listenToChild="listenToEdit"></bindChild>
      <removeChild :userId="userId"  v-if="isBind&&bindType===2" @listenToChild="isBind=false"></removeChild>
      <!--      <product :uId="userId"  v-if="isBind&&bindType===3" @listenToChild="isBind=false"></product>-->
    </el-dialog>
  </div>
</template>

<script>

import edit from "./edit";
import importData from "../../system/limit/importData";
import commons from "../../../utils/common";
import {delData, listData} from "@/api/data/user";
import {getBtn} from "../../../utils/btnAuth";
import {restUrl} from "../../../../url";
import {getToken} from "../../../utils/auth";
import bindChild from './bindChild'
import removeChild from "./removeChild";
import changeSale from "./changeSale";
import mergeUser from "./mergeUser";
import addPhoneUser from "./addPhoneUser"
import product from '../product/index'
import {refereeList} from "@/api/sys/user";
import {formatTree} from "@/utils/menuAuth";

export default {
  components: {
    edit,
    importData,
    bindChild,
    removeChild,
    changeSale,
    mergeUser,
    addPhoneUser,
    product
  },
  data() {
    return {
      status:'',
      statusOption:[{id:'',name:'全部'},{id:1,name:'正常'},{id:0,name:'冻结'}],
      keyword:'',
      currentPage: 1,
      pageSize: 15,
      totals: 0,
      loading: false,
      tableInfo:[],
      isPop: false,
      userId: '',
      isImport: false,
      importData: {},
      uploadUrl: restUrl + '/data/user/importUsers',
      token: getToken(),
      param: {folder: 'water'},
      btn:{},
      isBind:false,
      bindType:1,
      userName:'',
      isChangeSale:false,
      refereeId:'',
      type:'',
      remark:'',
      isMerge:false,
      isAddPhoneUser:false,
      opType:'',
      sortNumber:'',
      refereeOption:[],
      refereeIds:'',
      userInfo:{},
      userType:'',
      id:''
    }
  },
  mounted() {
    this.btn = getBtn();
    if (this.btn.query){
      this.getTableInfo(1);
    }
    this.getRefereeList();
    //获取用户类型
    let info = localStorage.getItem('water_user')
    this.userInfo = info?JSON.parse(info).loginUser:'';
    this.userType = this.userInfo.type;
  },
  methods: {
    //监听列表排序
    getChange(val) {
      if(val.prop=='money' || val.prop=='modifyTime') {
        return;
      }

      let sort = parseInt(val.prop)

      if(this.sortNumber < 0) {
        this.sortNumber = sort;
      }else {
        this.sortNumber = -sort;
      }
      this.getTableInfo(1);

    },
    getRefereeList() {
      refereeList().then((res)=> {
        this.refereeOption = res;
      })
    },
    closeBind() {
      this.isBind = false;
      this.getTableInfo(this.currentPage);
    },
    // 获取列表信息
    getTableInfo(page) {
      let that = this;
      that.loading = true;
      that.currentPage = page;
      let queryParams = {
        limit:that.pageSize,
        page:page,
        keyword:that.keyword,
        enable:that.status,
        userId:that.id,
        sort:that.sortNumber,
        refereeId:that.refereeIds
      }
      listData(queryParams).then(res => {
        that.tableInfo = res?res.list:[];
        that.totals = res?res.count:0;
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },
    //数值超过两位小数时候保留两位小数
    finalNum(item) {
      item = item * 100;
      var  y = String(item).indexOf( "." ) + 1;
      if (y > 0) {
        return parseFloat(item.toFixed(2));
      }  else  {
        return item;
      }
    },
    // 重置
    resetTable() {
      this.pageSize = 15;
      this.keyword = '';
      this.status = '';
      this.sortNumber = '';
      this.refereeIds = '';
      this.id = '';
      this.getTableInfo(1)
    },

    //跳转用户相关页面
    gotoDetail(obj,type) {
      let that = this;
      let url = type===1?'/user/product':(type===2?'/user/address':(type===3?'/user/log':(type===4?'/order/list':type===5?'/order/reserve':(type===6?'/order/productReturn':'/order/changeOrder'))));
      let parent = type<=3?'用户管理':'订单管理';
      that.$router.push({
        path: url,
        query: {
          key:formatTree(parent,url),
          userId: obj.id,
          username: obj.wxName+(obj.remark?'('+obj.remark+')':'')
        }
      })
    },

    //替换销售
    changeSales(obj,type) {
      this.isChangeSale = true;
      this.userId = obj.id;
      this.type = type
    },

    //合并用户
    openMerge(type,opType) {
      if(type === 1) {
        this.isMerge = true;
        this.opType = opType;
      } else {
        this.isAddPhoneUser = true;
      }
    },

    bindUserChild(obj,type){
      this.isBind = true;
      this.userId = obj.id;
      this.bindType = type;
      this.userName = obj.wxName;
    },

    // 删除
    deleteItem(obj,index) {
      let that = this;
      that.$confirm('确定'+(obj.enable===0?'冻结':'解冻')+obj.wxName+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {userId:obj.id,enable:obj.enable}
        return delData(param);
      }).then(() => {
        that.getTableInfo(that.currentPage);
        let msg = ''
        if(type == 0 ? msg='冻结' :msg="解冻")
          that.$message.success({
            message:msg + '成功',
            duration:1500
          });
      }).catch(() => {
        //重置
        that.tableInfo[index].enable = obj.enable == 0 ? 1:0;
      });
    },

    // excel导入
    importSuccess(res) {
      if (res.success) {
        if (res.data.failedCount) {
          this.isImport = true;
          this.importData = res.data
        } else {
          this.$message.success({
            message:'全部导入成功！',
            duration:1500
          });
          this.getTableInfo(this.currentPage)
        }
      } else {
        this.$message.error({
          message:res.message,
          duration:1500
        })
      }
    },

    // 打开弹窗
    openPopup(id) {
      this.isPop = true;
      this.userId = id;
    },

    listenToEdit(e){
      this.isPop = false;
      this.isChangeSale = false;
      this.isMerge = false;
      this.isBind = false;
      this.isAddPhoneUser = false;
      if (e.refresh){
        this.getTableInfo(this.currentPage)
      }
    },

    formatTime(time){
      return commons.formatTime(time)
    },

    sizeChange(val){
      this.pageSize =val;
      this.getTableInfo(1)
    },

    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
    },
  }
}
</script>

<style scoped>
.check_btn {
  color: #f7ab20;
}
.color {
  color: #c60000;
}

.rate {
  display: inline-block;
  color: #e40000;
  width: 60px
}
</style>
